package cn.wolfcode.shop.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;

import cn.wolfcode.shop.domain.Catalog;
import cn.wolfcode.shop.domain.SkuProperty;
import cn.wolfcode.shop.domain.SkuPropertyValue;
import cn.wolfcode.shop.service.ICatalogService;
import cn.wolfcode.shop.service.ISkuPropertyService;
import cn.wolfcode.shop.service.ISkuPropertyValueService;
import cn.wolfcode.shop.vo.JSONResult;

@Controller
@RequestMapping("/skuPropertys")
public class SkuPropertyController {

	@Reference
	private ICatalogService catalogService;

	@Reference
	private ISkuPropertyService propertyService;

	@Reference
	private ISkuPropertyValueService propertyValueService;

	/**
	 * 获取商品分类属性
	 * @param model
	 * @return
	 */
	@GetMapping("/view")
	public String view(Model model) {
		List<Catalog> cataloglist = catalogService.getCataloglist();
		String catalogJson = JSON.toJSONString(cataloglist);
		model.addAttribute("allCatalog", catalogJson);
		return "property/property";
	}

	/**
	 * 新增或者保存
	 * @return
	 */
	@PostMapping
	@ResponseBody
	public JSONResult saveOrUpdate(SkuProperty entity) {
		propertyService.saveOrUpdate(entity);
		return new JSONResult();
	}

	/**
	 * s通过分类属性id,删除分类属性
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public JSONResult delete(@PathVariable Long id) {
		propertyService.delete(id);
		return new JSONResult();
	}

	/**
	 * 页面中需要共享propertyId,需要配置@PathVariable("propertyId")????
	 * 
	 * @return
	 */
	@GetMapping("/{propertyId}/skuPropertyValues")
	private String showPropertyValue(@PathVariable("propertyId") Long id, Model model) {
		List<SkuPropertyValue> propertyValueList = propertyValueService.getPropertyValueList(id);
		model.addAttribute("propertyValueList", propertyValueList);
		return "property/property_value_list";
	}

	/**
	 * 通过sku属性的id获取该sku属性下属性值集合(以table的html代码片段的方式返回)
	 * /skuPropertys/"+skuPropertyId+"/skuPropertyValues/table
	 * skuPropertyValues/table
	 * @return
	 */
	@GetMapping("/{skuPropertyId}/skuPropertyValues/table")
	public String getSkuPropertyValueTable(Model model, @PathVariable Long skuPropertyId) {
		SkuProperty skuProperty = propertyService.getById(skuPropertyId);
		List<SkuPropertyValue> skuPropertyValueList = propertyValueService.getPropertyValueList(skuPropertyId);
		model.addAttribute("skuProperty",skuProperty);
		model.addAttribute("skuPropertyValueList",skuPropertyValueList);
		return "product_sku/sku_property_value_table";
	}
}
